package com.projectbox.web;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.projectbox.dao.UserDao;
import com.projectbox.model.User;

@Controller
@RequestMapping("/api/login")
public class LoginAPIController {

	private Logger logger = LoggerFactory.getLogger(getClass()); 
	
	private UserDao userDao;
	private PasswordEncoder passwordEncoder;
	
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> processNewProjectSubmission(@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password) {
		
		this.logger.debug("A iphone user tries to login with " + username + " " + password);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("valid", false);
		
		User user = this.userDao.getUserByUserName(username);
		if (user == null) {
			return map;
		}
		
		String encodePass = this.passwordEncoder.encodePassword(password, null); // encode the supply password
		logger.debug("the encode password is " + encodePass);
		
		if (encodePass.equals(user.getPassword())) {	// check the supply with the password in the DB
			map.put("valid", true);
			map.put("id", user.getId());
		}
		
		return map;
	}
}
